//
//  FriendIMNet.m
//  SportSocial
//
//  Created by yull on 14/12/23.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "FriendIMNet.h"
#import "PrivateMsgDao.h"
#import "ChatSystemInfo.h"
#import "ChatSysInfoDao.h"

@implementation FriendIMNet

+ (instancetype)shareInstance
{
    static FriendIMNet *friendNet = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        friendNet = [[FriendIMNet alloc] init];
    });
    return friendNet;
}

- (instancetype)init
{
    if (self = [super init]) {
        NSArray *pidArray = @[[NSNumber numberWithInteger:Friend_List_Receive_PID],
                          [NSNumber numberWithInteger:Friend_Notify_Receive_PID]];
        [self.arrayPid addObjectsFromArray:pidArray];
    }
    return self;
}

#pragma mark - 发送消息
//Ack私聊消息
- (void)sendFriendMsgAckWithMsgArray:(NSArray *)msgArray
{
    FriendNotifyCGMessage_Builder *builder = [FriendNotifyCGMessage builder];
    for (FriendNotifyMessage *message in msgArray) {
        builder = [builder addMsgIds:message.msgId];
    }
    
    FriendNotifyCGMessage *ackMsg = [builder build];
    NSData *data = [ackMsg data];
    
    [[IM_Service instance] sendData:data protocolId:Friend_Notify_Send_PID];
}

#pragma mark - 收到消息
- (void)handlePacketWithPid:(NSInteger)pid recvData:(NSData *)recvData
{
    switch (pid) {
        case Friend_List_Receive_PID:
            [self handleFriendListWithRecvData:recvData];
            break;
        case Friend_Notify_Receive_PID:
            [self handleFriendNotifyWithRecvData:recvData];
            break;
        default:
            [super handlePacketWithPid:pid recvData:recvData];
            break;
    }
}

//好友列表
- (void)handleFriendListWithRecvData:(NSData *)recvData
{
    FriendListGCMessage *friendListMsg = [FriendListGCMessage parseFromData:recvData];
    
    [CurrentUser shareInstance].friendMd5 = friendListMsg.md5;
    [CurrentUser shareInstance].friendList = friendListMsg.friendListList;
}

//私聊消息广播
- (void)handleFriendNotifyWithRecvData:(NSData *)recvData
{
    FriendNotifyGCMessage *friendNotifiMsg = [FriendNotifyGCMessage parseFromData:recvData];
    
    NSMutableArray *chatInfoArray = [NSMutableArray array];
    for (FriendNotifyMessage *message in friendNotifiMsg.messageListList) {
        [chatInfoArray addObject:[ChatSystemInfo systemInfoWithFriendMsg:message]];
    }
    
    BOOL ret = [[ChatSysInfoDao shareInstance] addChatInfoArray:chatInfoArray];
    
    if (ret) {
        NSLog(@"好友消息存储成功!");
        
        [SoundManager playSound];
        
        [self sendFriendMsgAckWithMsgArray:friendNotifiMsg.messageListList];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ChatSystemInfoReload" object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ChatInfoReload" object:nil];
    }
}

@end
